package com.frame.util;

import java.io.UnsupportedEncodingException;

/**
 * @author LRC
 * @createDate 2015年5月19日
 * @description 文字转码
 */
public class BITCoder {

	public static void main(String[] args) {
		String str = "{a:'你好',b:0.11,c:tttt}";
		String e = encode(str);
		String d = decode(e);
		System.out.println(e);
		System.out.println(d);
	}
	public static String hex = "0123456789ABCDEF";
	public static String encode(String str) {
		if(str==null||"".equals(str))return null;
		StringBuffer sb = new StringBuffer();
		byte[] data = null;
		try {
			data = str.getBytes("gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < data.length; i++) {
			String d = hex.charAt(data[i]>>4&0x0F) +""+hex.charAt(data[i]&0x0F);
			sb.append(d);
		}
		return sb.toString();
	}
	
	public static String decode(String code) {
		if(code==null||"".equals(code)||code.length()%2!=0)return null;
		int len = code.length() / 2;
		byte[] data = new byte[len];
		for (int i = 0; i < len; i++) {
			String subData = code.substring(i * 2, (i + 1) * 2);
			int d = Integer.parseInt(subData, 16);
			data[i] = (byte)d;
		}
		try {
			return new String(data, "gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
}
